package com.taxi.driver.module.order.address;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qianxx.utils.TypeUtils;
import com.qianxx.view.HeadView;
import com.taxi.driver.R;
import com.taxi.driver.common.BaseActivity;
import com.taxi.driver.config.IConstants;
import com.taxi.driver.event.MapEvent;
import com.taxi.driver.module.order.address.dagger.ChangeAddrModule;
import com.taxi.driver.module.order.address.dagger.DaggerChangeAddrComponent;
import com.taxi.driver.module.vo.AddressVO;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 功能描述：
 */
public class ChangeAddrActivity extends BaseActivity implements ChangeAddrContract.View {

    public static void actionStart(Context context, AddressVO vo) {
        Intent intent = new Intent(context, ChangeAddrActivity.class);
        if (vo != null) intent.putExtra(IConstants.PARAMS, vo);
        context.startActivity(intent);
    }

    ViewHolder mHolder;
    @BindView(R.id.head_view)
    HeadView mHeadView;
    @BindView(R.id.tv_city)
    TextView mTvCity;
    @BindView(R.id.ed_input)
    EditText mEdInput;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    private ChangeAddrAdapter mAdapter;
    private AddressVO mOriginalAddr;
    private List<AddressVO> mHistory; //历史记录
    private boolean mIsHistory = true; //当前是否显示历史记录
    private String mProvince;
    private String mCity;

    @Inject
    ChangeAddrPresenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_addr);
        ButterKnife.bind(this);
        DaggerChangeAddrComponent.builder()
                .appComponent(getAppComponent())
                .changeAddrModule(new ChangeAddrModule(this))
                .build().inject(this);
        mProvince = mPresenter.getProvince();
        mCity = mPresenter.getCurrentCity();
        mHistory = mPresenter.getHistoryAddr();
        getExtra();
        initUI();
    }

    private void getExtra() {
        Serializable obj = getIntent().getSerializableExtra(IConstants.PARAMS);
        if (obj != null) mOriginalAddr = (AddressVO) obj;
    }

    private void initUI() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ChangeAddrAdapter(this, R.layout.item_change_addr);
        View topView = LayoutInflater.from(this).inflate(R.layout.layout_change_addr_header, mRecyclerView, false);
        mHolder = new ViewHolder(topView);
        mAdapter.addHeaderView(topView);
        mRecyclerView.setAdapter(mAdapter);
        mHolder.mLayoutItem.setOnClickListener(v -> {
            if (mOriginalAddr == null) return;
            EventBus.getDefault().post(new MapEvent(MapEvent.VIEW_CHANGE_ADDR, mOriginalAddr)); //选择地址
            finish();
        });
        mAdapter.setOnClickListener(R.id.layout_item, (position, view, item) -> {
            selectAddr(item); //选择地址
        });
        mEdInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString().trim();
                mIsHistory = TextUtils.isEmpty(keyword);
                if (mIsHistory) {
                    showHistroryAddr(); //显示历史记录
                } else {
                    mPresenter.searchAddr(mCity, keyword); //根据关键字，搜索地址
                }
            }
        });
        mTvCity.setOnClickListener(v -> { //选择城市
            CitiesActivity.actionStart(this, mProvince, mCity);
        });
        showOriginAddr(); //显示原始地址
        showHistroryAddr(); //显示历史记录
        showCity(); //显示城市
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public void showOriginAddr() {
        if (mOriginalAddr == null) {
            gone(mHolder.mLayoutItem, mHolder.mTvTag);
            return;
        }
        visible(mHolder.mLayoutItem, mHolder.mTvTag);
        mHolder.mTvAddr.setText(TypeUtils.getValue(mOriginalAddr.getAddress()));
        mHolder.mTvDetail.setText(TypeUtils.getValue(mOriginalAddr.getAddressDetail()));
    }

    @Override
    public void showHistroryAddr() {
        mAdapter.setAll(mHistory); //显示历史记录
    }

    @Override
    public void showCity() {
        mTvCity.setText(TypeUtils.getValue(mCity)); //显示城市
    }

    @Override
    public void showSearchedAddr(List<AddressVO> list) {
        if (mIsHistory) return;
        mAdapter.setAll(list);
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void selectAddr(AddressVO vo) {
        if (vo == null || vo.getLatLng() == null) {
            toast("未获取到地址坐标");
            return;
        }
        if (!vo.isSaved()) vo.save(); //保存地址 TODO 数据的保存待调整
        EventBus.getDefault().post(new MapEvent(MapEvent.VIEW_CHANGE_ADDR, vo)); //选择地址
        finish();
    }

    static class ViewHolder {

        @BindView(R.id.tv_addr)
        TextView mTvAddr;
        @BindView(R.id.tv_detail)
        TextView mTvDetail;
        @BindView(R.id.layout_item)
        LinearLayout mLayoutItem;
        @BindView(R.id.tv_tag)
        TextView mTvTag;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == CitiesActivity.RESULT) {
            mProvince = data.getStringExtra(IConstants.PROVINCE);
            mCity = data.getStringExtra(IConstants.CITY);
            showCity(); //显示城市

            /* 执行搜索，刷新数据 */
            String keyword = mEdInput.getEditableText().toString().trim();
            if (!TextUtils.isEmpty(keyword)) mPresenter.searchAddr(mCity, keyword);
        }
    }

}
